package com.biyabi.service.impl;

import com.biyabi.entity.Product;
import com.biyabi.pojo.Collection;
import com.biyabi.service.CollectionService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service("collectionService")
public class CollectionServiceImpl implements CollectionService {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public void add(String userId, Product product) {
        String redisKey = DigestUtils.md5DigestAsHex((userId + "collection").getBytes());
        ValueOperations colredis = redisTemplate.opsForValue();
        Collection mycol = (Collection)colredis.get(redisKey);
        if(mycol!=null){
            Map<String, Product> pros = mycol.getPros();
            if(!pros.containsKey(product.getId())){
                pros.put(product.getId(),product);
                colredis.set(redisKey,mycol);
            }
        }else{
            mycol = new Collection();
            mycol.setPros(new HashMap<String, Product>());
            Map<String, Product> pros = mycol.getPros();
            pros.put(product.getId(),product);
            colredis.set(redisKey,mycol);
        }

    }

    @Override
    public void delete(String userId, String productId) {
        String redisKey = DigestUtils.md5DigestAsHex((userId + "collection").getBytes());
        ValueOperations colredis = redisTemplate.opsForValue();
        Collection mycol = (Collection)colredis.get(redisKey);
        //如果存在该商品id，则删除后，在存入redis中，否则不做任何操作
        if(mycol!=null){
            Map<String, Product> pros = mycol.getPros();
            if(pros.containsKey(productId)){
                pros.remove(productId);
                colredis.set(redisKey,mycol);
            }
        }
    }

    @Override
    public Map<String,Product> selectAllMy(String userId) {
        String redisKey = DigestUtils.md5DigestAsHex((userId + "collection").getBytes());
        ValueOperations colredis = redisTemplate.opsForValue();
        Collection mycol = (Collection)colredis.get(redisKey);
        return mycol.getPros();
    }
}
